package org.finjic.context;

import org.finjic.entity.BeanDefinition;
import org.finjic.factory.BeanFactory;
import org.finjic.factory.BeanFactoryImpl;
import org.finjic.xml.ConfigSaxHandler;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.util.Set;

/**
 * User: Anton Pets Date: 11.11.12
 */
public class XmlApplicationContext extends AbstractApplicationContext {
    private Set<BeanDefinition> beans;

    public XmlApplicationContext(String configFileName) {
        beans = doSaxParsing(configFileName);
    }

    @Override
    protected BeanFactory getBeanFactory() {
        return new BeanFactoryImpl(beans);
    }

    private Set<BeanDefinition> doSaxParsing(String file) {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();
            ConfigSaxHandler handler = new ConfigSaxHandler();
            saxParser.parse(file, handler);
            return handler.getBeans();
        } catch (Exception e) {
            throw new RuntimeException(e.getCause());
        }
    }
}
